using System;
using System.Text;
using System.Globalization;
using System.Collections.Generic;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.IO;
using System.Configuration;
using Microsoft.SharePoint.Utilities;
using System.Reflection;
using System.Collections;

namespace CKS.FormsBasedAuthentication
{

    class FormsBasicAuthFeatureReceiver : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWebApplication oApp = (SPWebApplication)properties.Feature.Parent;

            oApp.WebConfigModifications.Add(CreateModification("add[@name='CKS.FBAModule']",
                                                               "configuration/system.web/httpModules",
                                                               string.Format("<add name='CKS.FBAModule' type='{0}' />", typeof(BasicAuthenticationModule).AssemblyQualifiedName)));
          

            oApp.Update();

            SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
        }

        protected SPWebConfigModification CreateModification(string name, string path, string value)
        {
            SPWebConfigModification oModification = new SPWebConfigModification(name, path);
            oModification.Owner = "CKS.FBAModule";
            oModification.Value = value;
            oModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;

            return oModification;
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWebApplication oApp = (SPWebApplication)properties.Feature.Parent;

            List<SPWebConfigModification> toRemove = new List<SPWebConfigModification>();

            foreach (SPWebConfigModification m in oApp.WebConfigModifications)
            {
                if (m.Owner == "CKS.FBAModule")
                    toRemove.Add(m);
            }

            foreach (SPWebConfigModification m in toRemove)
                oApp.WebConfigModifications.Remove(m);

            oApp.Update();

            SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
        }
    }
}
